package com.heny.demo.util;

import com.heny.demo.constants.EPSGConst;
import com.heny.demo.entity.TurnPoint;
import org.geotools.geometry.jts.JTS;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;

/**
 * 通用坐标系转换工具
 *
 * @author 邢益萌
 * {@code @date} 2025/9/12 13:30
 */
public class GeometryUtil {

    private static final GeometryFactory geometryFactory = new GeometryFactory();

    /**
     * 创建坐标点
     */
    public static Point createPoint(double x, double y, int srid) {
        Point point = geometryFactory.createPoint(new Coordinate(x, y));
        point.setSRID(srid);
        return point;
    }

    /**
     * 坐标系转换
     *
     * @param point  输入点
     * @param source 源坐标系（例如 CGCS2000 / 3-degree Gauss-Kruger CM 114E  EPSG:4547）
     * @param target 目标坐标系（例如 EPSG:4326）
     */
    public static Point transform(Point point, int source, int target) {
        try {
            CoordinateReferenceSystem sourceCRS = CRS.decode("EPSG:" + source, true);
            CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:" + target, true);
            //坐标系转换
            MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS, true);
            //解析为Geometry对象
            Geometry targetGeometry = JTS.transform(point, transform);
            targetGeometry.setSRID(target);

            return (Point) targetGeometry;
        } catch (Exception e) {
            throw new RuntimeException("坐标系转换失败: EPSG:" + source + " -> EPSG:" + target, e);
        }
    }

    /**
     * 将文件中每行字符串转换为坐标对象
     * @param arr 每行字符串数组
     * @return 解析后的坐标对象
     */
    public static TurnPoint getTurnPoint(String[] arr){
        //创建对象
        TurnPoint tp = new TurnPoint();
        String index = arr[0];
        double x = Double.parseDouble(arr[1]);
        double y = Double.parseDouble(arr[2]);
        //构建坐标
        Point point = createPoint(x, y, EPSGConst.EPSG_4547);
        //转换为目标坐标
        Point converted = transform(point, EPSGConst.EPSG_4547,EPSGConst.EPSG_4326);

        tp.setIndex(index);
        tp.setCoordinate(converted);
        return tp;
    }
}
